//
//  ThirdViewController.m
//  XDCommonApp
//
//  Created by XD-XY on 2/12/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "ThirdViewController.h"

#import "XDHeader.h"
#import "XDTools.h"
#import "WorkSecondVC.h"
#import "SearchItem.h"
#import "SearchCell.h"
#import "WaterDetailViewController.h"
#import "DetailforArtistVC.h"
#import "MostDetailViewController.h"
#define dHeightForHeader 0

@interface ThirdViewController ()

{
    NSArray *allArray;
}

@end

@implementation ThirdViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_searchDataArray removeAllObjects];
    [_searchTableView reloadData];
    searchView.mytextField.text = nil;
    _searchBgview.hidden=YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    [[NSUserDefaults standardUserDefaults] setObject:@"yes" forKey:@"SecondViewHiddenSearch"];
    
    self.leftBtn.hidden =YES;
    allArray = [[NSArray alloc]init];
    
    self.searchDataArray = [[NSMutableArray alloc] init];
    
    searchView = [[XDSearchView alloc] initWithFrame:CGRectMake(0,0, UI_SCREEN_WIDTH, 97/2.0f)];
    [searchView setBgViewRect:CGRectMake(20/2.0f, 19/2.0f, 300, 50/2.0f)];
    searchView.delegate = self;
    [self.navigationBarView addSubview:searchView];
    
    
    [self getXmlData];
}

-(void)initSearchTableView
{
    self.searchBgview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, self.contentView.frame.size.height)];
    _searchBgview.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:_searchBgview];
    
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, self.contentView.frame.size.height-252) style:UITableViewStylePlain];
    _searchTableView.backgroundColor = [UIColor whiteColor];
    _searchTableView.dataSource = self;
    _searchTableView.delegate =self;
    [_searchBgview addSubview:_searchTableView];
    _searchBgview.hidden =YES;
}

- (void)initWidget
{
    self.detailActTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,.0f, UI_SCREEN_WIDTH,self.contentView.frame.size.height-49) style:UITableViewStylePlain];
    _detailActTableView.delegate = self;
    _detailActTableView.dataSource = self;
    _detailActTableView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:_detailActTableView];
    [self initSearchTableView];
    
}

#pragma mark ---------------XDSearchView Delegate----------
-(void)XDSearhViewShouldBeginEditing
{
    DDLOG_CURRENT_METHOD;
    [_searchDataArray removeAllObjects];
    [_searchTableView reloadData];
    _searchBgview.hidden =NO;
}

-(void)XDSearchViewShouldReturn
{
    DDLOG_CURRENT_METHOD;
    _searchTableView.frame = _searchBgview.bounds;
}

-(void)XDSearchViewCanelbuttonClick
{
    DDLOG_CURRENT_METHOD;
    searchView.mytextField.text = nil;
    [_searchDataArray removeAllObjects];
    _searchBgview.hidden = YES;
}

-(void)XDSearchTextFieldDidChange
{
    DDLOG_CURRENT_METHOD;
    [self getSearchData:searchView.mytextField.text];
}


#pragma mark  --------------tableView delegate----------------

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView ==_searchTableView){
        return [_searchDataArray count];
    }
    return allArray.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return dHeightForHeader;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //    NSArray * array;
    CGFloat headerHeight=0;
    if (tableView == _detailActTableView){
        
        //        array=@[@"2014年2月22日 星期一",@"2012年2月24日 星期三"];
        headerHeight = dHeightForHeader;
    }
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, headerHeight)];
    view.backgroundColor = RGBA(217, 217, 217, 1);
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, UI_SCREEN_WIDTH-15, headerHeight)];
    label.textColor = TEXTBLACKCOLORE;
    label.font = [UIFont systemFontOfSize:15];
    label.backgroundColor = [UIColor clearColor];
    //    label.text = [array objectAtIndex:section];
//    label.text = activityDate;
    
    [view addSubview:label];
    return view;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 150;
    return 60;
}


-(UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == _detailActTableView){
        static NSString * cellName = @"cell";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if (cell == nil){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
            cell.backgroundColor = [UIColor clearColor];
        }
        
        if (allArray.count >0) {
            cell.textLabel.text = [[allArray objectAtIndex:indexPath.row]valueForKey:@"categoryName"];
            
            UIImageView *nextLvIV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"launh_sure@2x"]];
            nextLvIV.frame = CGRectMake(290, 20, 15, 20);
            nextLvIV.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:nextLvIV];
            
        }
        //        [cell.contentView addSubview:specialMediaLabel];
        
        return cell;
    }
    else if(tableView == _searchTableView){
        static NSString * cellName = @"cell2";
         SearchCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if (cell == nil){
            cell = [[SearchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
            cell.backgroundColor = [UIColor whiteColor];
        }
        if ([_searchDataArray count]==0){
            return cell;
        }
        SearchItem * item = [_searchDataArray objectAtIndex:indexPath.row];
        cell.headerIamgeView.image = [UIImage imageNamed:@"searchworkIcon"];
        cell.titleLabel.text = [NSString stringWithFormat:@"%@   %@",item.ArtistName,item.ArtworkName];
        return cell;
    }
    
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
 
    if (tableView == _searchTableView){
////        SearchItem * item = [_searchTableView al]
//        WaterDetailViewController *waterVC = [[WaterDetailViewController alloc] init];
////        waterVC.artistId = _idStr;
//        
//        waterVC.classID = @"水墨";
//        waterVC.subID = @"人物";
//        [self.navigationController pushViewController:waterVC animated:YES];
        SearchItem * item = [_searchDataArray objectAtIndex:indexPath.row];
        DDLOG(@"_searchDataArray.count = %d   inexPath.row = %d",[_searchDataArray count],indexPath.row);
     
        MostDetailViewController *mostVC = [[MostDetailViewController alloc] init];
        mostVC.idStr = item.ArtistType;
        [self.navigationController pushViewController:mostVC animated:YES];
    }else{
        WorkSecondVC *sVC = [[WorkSecondVC alloc]init];
        sVC.catID = [[allArray objectAtIndex:indexPath.row]valueForKey:@"categoryId"];
        sVC.catname = [[allArray objectAtIndex:indexPath.row]valueForKey:@"categoryName"];
        [self.navigationController pushViewController:sVC animated:YES];

    }
}

#pragma mark  -------- DataSouceManager------------

- (void)getXmlData
{
    NSString *id_Str = @"null";
    //        NSString *type_Str = _typeStr;

    
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <WorkListCategory xmlns=\"http://tempuri.org/\">"
                          "<key>%@</key>"
                          "</WorkListCategory>",id_Str];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:WORKLISTCATEGORY];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    DDLOG(@"res = %@",responseDict);
                    
                    allArray = [responseDict valueForKey:@"categoryList"];
//                    activityDate = [responseDict valueForKey:@"activityDate"];
//                    activityTime = [responseDict valueForKey:@"activityTime"];
//                    programTitle = [responseDict valueForKey:@"programTitle"];
//                    programContent = [responseDict valueForKey:@"programContent"];
            
                    
                    [self initWidget];
                    
                    
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
    
}


-(void)getSearchData:(NSString *)string
{
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <SearchPics_2 xmlns=\"http://tempuri.org/\">"
                          "<keyword>%@</keyword>"
                          "<pageidx>0</pageidx>"
                          "<limit>50</limit>"
                          "</SearchPics_2>",string];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:SEARCHPICS];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    //表示请求成功
                    int curpage = [[responseDict objectForKey:@"curpage"] intValue]; //当前页
                    int tatalPage = [[responseDict objectForKey:@"totalpage"] intValue]; // 总页数
                    [_searchDataArray removeAllObjects];
                    for (NSDictionary * dic in [responseDict objectForKey:@"nameList"]){
                        SearchItem * item = [[SearchItem alloc] init];
                        item.ArtistName = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ArtistName"]];
                        if ([item.ArtistName isEqualToString:@"<null>"]) {
                            item.ArtistName = @"";
                        }
                        item.ArtworkId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ArtworkId"]];
                        item.ArtworkName = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ArtworkName"]];
                        item.color = [NSString stringWithFormat:@"%@",[dic objectForKey:@"color"]];
                        item.picid = [NSString stringWithFormat:@"%@",[dic objectForKey:@"picid"]];
                        item.picurl_s = [NSString stringWithFormat:@"%@",[dic objectForKey:@"picurl_s"]];
                        item.size = [NSString stringWithFormat:@"%@",[dic objectForKey:@"size"]];
                        item.ArtistType = [NSString stringWithFormat:@"%@",[dic objectForKey:@"type"]];
                        if ([item.ArtistType isEqualToString:@"0"]) {
                            [_searchDataArray addObject:item];
                        }
                        
                    }
                    [_searchTableView reloadData];
                    
                }
            }
        }];
        
        [request setFailedBlock:^{
//            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
//        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
